﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using YXChatFormClient.Dtos;
using YXChatFormClient.Dtos.Buddy;
using YXChatFormClient.Utility;

namespace YXChatFormClient.UserControls
{
    public partial class UC_ChatItem : UserControl
    {
        public delegate void ChatClickHandler(object sender, EventArgs e, ChatRecordAccountDto ChatRecord);
        public event ChatClickHandler ChatClick;
        /// <summary>
        /// 最后一条聊天记录和对应用户
        /// </summary>
        public ChatRecordAccountDto ChatRecordAccount { get; set; }
        public UC_ChatItem()
        {
            InitializeComponent();
            //设置控件样式
            SetStyle(
                    ControlStyles.AllPaintingInWmPaint | //不闪烁
                    ControlStyles.OptimizedDoubleBuffer //支持双缓存
                   , true);
        }

        private void UC_ChatItem_Click(object sender, EventArgs e)
        {
            foreach (Control itemControl in this.Parent.Controls)
            {
                if (itemControl.BackColor==Color.FromArgb(198,198,198))
                {
                    itemControl.BackColor = Color.Gainsboro;
                }
            }
            this.BackColor = Color.FromArgb(198, 198, 198);
            if (ChatClick != null) ChatClick(sender, e, ChatRecordAccount);
        }

        private void UC_ChatItem_Load(object sender, EventArgs e)
        {
            this.lbBuddyRemark.Text = ChatRecordAccount.Account.NickName;
            this.picAvatar.ImageLocation = ImageHelper.GetServerImage(ChatRecordAccount.Account.Avatar);
            if (ChatRecordAccount.ChatRecord.Any())
            {
                this.lbLastMsg.Text = ChatRecordAccount.ChatRecord[0]?.Content;
                this.lbLastMsgTime.Text = GetLastMsgTime(ChatRecordAccount.ChatRecord[0]?.CreateTime);
            }
        }

        protected string GetLastMsgTime(DateTime? lastMsgTime)
        {
            if (lastMsgTime.HasValue)
            {
                var currentDate = DateTime.Now;
                if (lastMsgTime.Value.Date == currentDate.Date)
                {
                    return lastMsgTime.Value.ToString("HH:mm");
                }
                else if (lastMsgTime.Value.Year == currentDate.Year)
                {
                    return lastMsgTime.Value.ToString("MM-dd");
                }
                else
                {
                    return lastMsgTime.Value.ToString("yyyy-MM-dd");
                }
            }

            return null;
        }

        private void UC_ChatItem_Paint(object sender, PaintEventArgs e)
        {
            UC_ChatItem_Load(null,null);
        }
    }
}
